package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.health.ProductVo;
import io.lettuce.core.BitFieldArgs;
import io.swagger.models.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备管理Service业务层处理
 * 
 * @author alexis
 * @date 2025-06-17
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IoTDAClient client;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备管理
     *
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id) {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备管理列表
     *
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     *
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备管理
     *
     * @param dto 设备管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDevice(DeviceDto dto) {
        //查询设备在不在
        Device device = getById(dto.getId());
        if (ObjectUtil.isEmpty(device)) {
            throw new BaseException("设备不存在");
        }
        //先更新设备
        //如果是随身设备，物理位置设为-1
        if (dto.getLocationType().equals(0)) {
            dto.setPhysicalLocationType(-1);
        }
        //修改数据库中的信息
        try {
            Device bean = BeanUtil.toBean(dto, Device.class);
            deviceMapper.updateDevice(bean);
        } catch (Exception e) {
            throw new BaseException("老人位置以改变，请重新选择");
        }
        //同步设备信息
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.setDeviceId(dto.getIotId());
        UpdateDevice updateDevice = new UpdateDevice();
        updateDevice.setDeviceName(dto.getDeviceName());
        request.setBody(updateDevice);
        client.updateDevice(request);
        return 1;
    }



    /**
     * 批量删除设备管理
     * 
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }



    //同步产品列表
    @Override
    public void syncProductList() {
        //请求参数
        ListProductsRequest request = new ListProductsRequest();
        //发起请求
        ListProductsResponse response = client.listProducts(request);
        if (response.getHttpStatusCode() != 200){
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        //存储到redis
        List<ProductSummary> products = response.getProducts();
        redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT_LIST,JSONUtil.toJsonStr(products));
    }

    @Override
    public List<ProductVo> allProduct() {
        //从Redis中查询数据
        String json = (String) redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_LIST);
        //如果数据为空，则返回空
        if (StringUtils.isEmpty(json)){
            return Collections.emptyList();
        }
        //解析数据并返回
        List<ProductVo> list = JSONUtil.toList(json, ProductVo.class);
        return list;
    }



    /*@Override
    public void syncProductList() {
        //请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        //设置条数
        listProductsRequest.setLimit(50);
        //发起请求
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if(response.getHttpStatusCode() != 200){
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        //存储到redis
        redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(response.getProducts()));
    }*/




   /* @Override
    public List<ProductVo> allProduct() {
        String jsonStr = (String) redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_LIST);
        if (StrUtil.isEmpty(jsonStr)){
            return Collections.emptyList();
        }
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }*/


    /*@Override
    public void registerDevice(DeviceDto dto) {
        //判断设备名是否重复
        Long count1 = lambdaQuery()
                .eq(Device::getDeviceName, dto.getDeviceName())
                .count();
        if (count1!=0 && count1>0){
            throw new BaseException("设备名称已存在");
        }
        Long count2 = lambdaQuery()
                .eq(Device::getNodeId, dto.getNodeId())
                .count();
        if (count2!=0 && count2>0){
            throw new BaseException("设备标识码已存在");
        }
        Long count3 = lambdaQuery()
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getPhysicalLocationType, dto.getPhysicalLocationType())
                .count();
        if (count3!=null && count3>0){
            throw new BaseException("同一位置已绑定相同产品");
        }
        //注册设备到华为云
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();
        addDevice.setNodeId(dto.getNodeId());
        addDevice.setDeviceName(dto.getDeviceName());
        addDevice.setProductId(dto.getProductKey());
        String secret = UUID.randomUUID().toString().replace("-", "");
        AuthInfo authInfo = new AuthInfo();
        authInfo.setSecret(secret);
        addDevice.setAuthInfo(authInfo);
        request.setBody(addDevice);
        AddDeviceResponse response;
        try {
            response = client.addDevice(request);
        } catch (Exception e) {
            throw new RuntimeException("调用华为云云SDK失败");
        }
        //同步到本地数据库

        Device bean = BeanUtil.toBean(dto, Device.class);
        bean.setHaveEntranceGuard(0);
        bean.setSecret(secret);
        bean.setIotId(response.getDeviceId());
        save(bean);
    }
*/

    @Override
    public void registerDevice(DeviceDto dto) {
        Long count1 = lambdaQuery()
                .eq(Device::getDeviceName, dto.getDeviceName())
                .count();
        if (count1!=0 && count1>0){
            throw new BaseException("设备名称已存在");
        }
        Long count2 = lambdaQuery()
                .eq(Device::getNodeId, dto.getNodeId())
                .count();
        if (count2!=0 && count2>0){
            throw new BaseException("设备标识码已存在");
        }
        Long count3 = lambdaQuery()
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getPhysicalLocationType, dto.getPhysicalLocationType())
                .eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .count();
        if (count3!=0 && count3>0){
            throw new BaseException("设备已存在");
        }
        //iot中新增设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.withProductId(dto.getProductKey());
        body.withDeviceName(dto.getDeviceName());
        body.withNodeId(dto.getNodeId());
        request.withBody(body);
        AuthInfo authInfo = new AuthInfo();
        //秘钥
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        authInfo.withSecret(secret);
        body.setAuthInfo(authInfo);
        request.setBody(body);
        AddDeviceResponse response;
        try {
            response = client.addDevice(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("调用华为云SDK失败");
        }
        //存储数据库
        Device bean = BeanUtil.toBean(dto, Device.class);
        bean.setHaveEntranceGuard(0);
        bean.setIotId(response.getDeviceId());
        bean.setSecret(secret);
        save(bean);

    }




    //查询设备详细数据
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //判断数据库中是否存在这个设备
        //sql: select * from device where iot_id = #{iotId}
        Device device = lambdaQuery()
                .eq(Device::getIotId, iotId)
                .one();
        if (device == null){
            throw new BaseException("设备不存在");
        }
        //获取华为云里边的字段
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response;
        try {
            response = client.showDevice(request);
        } catch (Exception e) {
            throw new RuntimeException("调用华为云SDK失败");
        }


        String status = response.getStatus();
        String activeTime = response.getActiveTime();
        //时间的类型转换
        OffsetDateTime offsetDateTime = OffsetDateTime.parse(activeTime);
        //将UTC时间转化为北京时间的localDateTime
        LocalDateTime beijingTime = offsetDateTime
                .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();
        //获取数据库中的字段
        DeviceDetailVo vo = BeanUtil.toBean(device, DeviceDetailVo.class);
        vo.setDeviceStatus(status);
        vo.setActiveTime(beijingTime);
        //封装合并，然后返回
        return vo;
    }











   /* @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //查询数据库中是否存在
        Device device = lambdaQuery()
                .eq(Device::getIotId, iotId)
                .one();
        if (device ==  null){
            throw new BaseException("设备不存在");
        }
        DeviceDetailVo vo = BeanUtil.toBean(device, DeviceDetailVo.class);
        //获取华为云平台的两个字段
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response;
        try {
           response =  client.showDevice(request);
        } catch (Exception e) {
            throw new BaseException("调用华为云SDK失败");
        }
        String status = response.getStatus();
        String activeTime = response.getActiveTime();
        vo.setDeviceStatus(status);
        //组装DeviceDetailVo然后返回
        OffsetDateTime offsetDateTime = OffsetDateTime.parse(activeTime);
        //将UTC时间转化为北京时间的localDateTime
        LocalDateTime beijingTime = offsetDateTime
                .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();
        vo.setActiveTime(beijingTime);
        return vo;
    }
*/


    //查询设备上报的数据





    @Override
    public AjaxResult queryServiceProperties(String iotId) {
        //从IoT里边获取设备属性
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        /*if (response.getHttpStatusCode()!=200){
            throw new BaseException("调用华为云SDK失败");
        }*/
        DeviceShadowProperties reported = response.getShadow().get(0).getReported();
        String eventTime = reported.getEventTime();

        //时间的类型转换

        // 定义输入格式
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX");

        // 解析为OffsetDateTime
        OffsetDateTime offsetDateTime = OffsetDateTime.parse(eventTime, inputFormatter);

        // 转换为LocalDateTime
        LocalDateTime beijingTime = offsetDateTime.toLocalDateTime();


        Object properties = reported.getProperties();
        JSONObject jsonObject = JSONUtil.parseObj(properties);
        List<Map<String, Object>> mapList = new ArrayList<>();
        jsonObject.forEach((key, value) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("functionId", key);
            map.put("value", value);
            map.put("eventTime", beijingTime);
            mapList.add(map);
        });
        return AjaxResult.success(mapList);
    }

    @Override
    public int deleteDeviceById(String iotId) {
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        client.deleteDevice(request);
        remove(new LambdaQueryWrapper<Device>().eq(Device::getIotId, iotId));
        return 1;
    }

























   /* @Override
    public AjaxResult queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        DeviceShadowProperties reported = response.getShadow().get(0).getReported();
        String eventTime = reported.getEventTime();
        //时间的类型转换

        // 定义输入格式
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX");

        // 解析为OffsetDateTime
        OffsetDateTime offsetDateTime = OffsetDateTime.parse(eventTime, inputFormatter);

        // 转换为LocalDateTime
        LocalDateTime beijingTime = offsetDateTime.toLocalDateTime();

        Object properties = reported.getProperties();
        JSONObject entries = JSONUtil.parseObj(properties);
        List<Map<String, Object>> list = new ArrayList<>();
        entries.forEach((key, value)->{
            Map<String, Object> map = new HashMap<>();
            map.put("functionId", key);
            map.put("eventTime", beijingTime);
            map.put("value", value);
            list.add(map);
        });
        return AjaxResult.success(list);

    }*/


}
